package com.haipumi.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.haipumi.beans.JsonModel;
import com.haipumi.beans.haipumi_admins;
import com.haipumi.beans.haipumi_skin;
import com.haipumi.beans.haipumi_user;
import com.haipumi.biz.IBackAdminBiz;
import com.haipumi.biz.IUserBiz;
import com.haipumi.biz.impl.BackAdminBizImpl;
import com.haipumi.biz.impl.UserBizImpl;
import com.haipumi.utils.CommonData;
import com.haipumi.utils.RequestUtil;

public class CustServlet extends CommonServlet {
	
	private static final long serialVersionUID = -7785215580559455677L;
	
	IUserBiz iub=new UserBizImpl();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//先从request里获取op选项为多少
		String op=request.getParameter("op");
		
		if("login".equals(op)){
			//调用login方法，并传入request 在bizimpl中再构建user对象
			login(request,response);
		}else if("register".equals(op)){
			//调用register方法，并传入request 在bizimpl中再构建user对象
			register(request,response);
		}else if("userlogout".equals(op)){
			userlogout(request,response);
		}else if("backlogin".equals(op)){
			//调用login方法，并传入request 在bizimpl中再构建user对象
			backlogin(request,response);
		}else if("activateuser".equals(op)){
			activateuser(request,response);
		}else if("savebaseinfo".equals(op)){
			savebaseinfo(request,response);
		}else if("changebackground".equals(op)){
			changebackground(request,response);
		}else if("savetel".equals(op)){
			savetel(request,response);
		}
		
	}

	
	private void savetel(HttpServletRequest request,
			HttpServletResponse response) {
		String uid=request.getParameter("uid");
		String uqq=request.getParameter("uqq");
		String utel=request.getParameter("utel");
		boolean flag=iub.saveTel(uid, uqq, utel);
		JsonModel jm=new JsonModel();
		if(flag){
			//保存成功
			jm.setCode(1);
			jm.setMsg("用户信息保存成功");
		}else{
			jm.setCode(0);
			jm.setMsg("用户信息保存失败，请联系管理员或重试...");
		}
		super.outData(response, jm);
	}


	private void changebackground(HttpServletRequest request,
			HttpServletResponse response) {
		String uid=request.getParameter("uid");
		String sid=request.getParameter("sid");
		haipumi_skin skin=null;
		skin=iub.changebackground(uid, sid);
		HttpSession session=request.getSession();
		JsonModel jm=new JsonModel();
		if(skin!=null){
			//更改成功了
			//修改session
			haipumi_user user=(haipumi_user) session.getAttribute(CommonData.USERSESSION);
			user.setSid(sid);
			user.setSimage(skin.getSimage());
			user.setScolor(skin.getScolor());
			session.setAttribute(CommonData.USERSESSION, user);
			jm.setCode(1);
			jm.setMsg("背景修改成功");
		}else{
			//失败了
			jm.setCode(0);
			jm.setMsg("用户背景修改失败，请联系管理员");
		}
		super.outData(response, jm);
				
	}


	private void savebaseinfo(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session=request.getSession();
		haipumi_user user=RequestUtil.parseRequest(request, haipumi_user.class);
		boolean flag=false;
		flag=iub.savebaseinfo(user);
		JsonModel jm=new JsonModel();
		if(flag){
			jm.setCode(1);
			//jm.setMsg("用户信息修改成功");
			haipumi_user backuser=iub.findUser(user.getUlogon());
			jm.setObj(backuser);
			//将用户重新存入session
			haipumi_user newbakcuser=(haipumi_user) session.getAttribute(CommonData.USERSESSION);
			newbakcuser.setUalais(user.getUalais());
			newbakcuser.setUname(user.getUname());
			newbakcuser.setUsex(user.getUsex());
			newbakcuser.setUinfo(user.getUinfo());
			session.setAttribute(CommonData.USERSESSION, newbakcuser);
			
		}else{
			jm.setCode(0);
			jm.setMsg("用户信息修改失败，请联系管理员");
		}
		super.outData(response, jm);
		
	}


	private void activateuser(HttpServletRequest request,
			HttpServletResponse response) {
		String ulogon=request.getParameter("ulogon");
		boolean flag=iub.activateUser(ulogon);
		PrintWriter out=null;
		HttpSession session=request.getSession();
		try {
			out=response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(flag){
			//用户状态已经激活，跳转到用户管理界面界面 alert语句
			// 先用该用户登录
			haipumi_user user=iub.findUser(ulogon);
			//haipumi_user backuser=iub.login(user);
			haipumi_user backuser =iub.newlogin(user);
			if(backuser!=null){
				//登录成功
				try {
					session.setAttribute(CommonData.USERSESSION, backuser);
//					out.print("<script>alert(\"用户已激活，请查看个人信息或修改...\");</script>");
//
//					out.flush();
//					out.close();
					response.sendRedirect("backcust/personinfo.jsp");
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				//登录失败
				try {
//					out.print("<script>alert(\"用户登录失败，请重新注册验证或联系管理员...\");</script>");
//					
//					out.flush();
//					out.close();
					response.sendRedirect("index.jsp");
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}else{
			//用户激活不成功
		}
	}


	private void backlogin(HttpServletRequest request,
			HttpServletResponse response) {
		JsonModel jm=new JsonModel();
		haipumi_admins admin=null;
		try {
			admin = RequestUtil.parseRequest(request, haipumi_admins.class);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//这里是登录的操作
		//取出用户名，密码,验证码
		HttpSession session=request.getSession();
		String codeSession=(String)session.getAttribute(CommonData.CODESESSION);
		//1.判断验证码是否ok
		if(!codeSession.equals(admin.getValcode())){
			jm.setCode(0);
			jm.setMsg("验证码错误");
		}else{
			//2.调用业务层，访问数据库，查看是否有这个用户
			IBackAdminBiz BackAdminBiz=new BackAdminBizImpl();
			
			haipumi_admins Backadmin=BackAdminBiz.backlogin(admin);
			if(Backadmin==null){//查无此人
				jm.setCode(0);
				jm.setMsg("用户名或密码不匹配、或者用户不存在、或该管理员已失效");
			}else{//查询到结果
				if(session.getAttribute(CommonData.SESSIONLOCATION)!=null){
					session.setAttribute(CommonData.ADMINSESSION, Backadmin);
					jm.setCode(2);
					jm.setMsg(session.getAttribute(CommonData.SESSIONLOCATION).toString());
				}else{
					session.setAttribute(CommonData.ADMINSESSION, Backadmin);
					jm.setCode(1);
					jm.setObj(Backadmin);
				}
			}
		}
		super.outData(response, jm);
		
	}


	/**
	 * 前端用，head中的注销事件，所有用户的注销事件，只会返回注销成功或失败
	 * @param request
	 * @param response
	 */
	private void userlogout(HttpServletRequest request,
			HttpServletResponse response) {
		JsonModel jm=new JsonModel();
		HttpSession session=request.getSession();
		haipumi_user user=null;
		user=(haipumi_user) session.getAttribute(CommonData.USERSESSION);
		if(user==null){
			jm.setCode(0);
			jm.setMsg("出现系统错误，3秒后，系统将帮您刷新页面...");
		}else{
			session.removeAttribute(CommonData.USERSESSION);
			jm.setCode(1);
		}
		super.outData(response, jm);
	}

	/**
	 *  	前端用，用户注册
	 * @param request
	 * @param response 
	 */
	private void register(HttpServletRequest request, HttpServletResponse response) {
		haipumi_user user=null;
		user=RequestUtil.parseRequest(request, haipumi_user.class);
		JsonModel jm=new JsonModel();
		String localhost=request.getParameter("localhref");
		localhost=localhost.substring(13);
		String [] localhostcontent=localhost.split("%2F");
		String localhref="";
		for(int i=0;i<localhostcontent.length;i++){
			localhref+=localhostcontent[i]+"/";
		}
		localhost.replace("%2F", "/");
		System.out.println(localhost);
		
		haipumi_user backuser=null;
		backuser=iub.findUser(user.getUlogon());
		if(backuser!=null){
			//用户已经注册
			
			haipumi_user unactivateuser=iub.findUnActivate(user.getUlogon());
			if(unactivateuser!=null){
				//证明已经注册，但为激活，重新发送信息
				boolean mailflag=iub.sendMail(user, localhref);
				if(mailflag){
					//再次发送成功
					jm.setCode(0);
					jm.setMsg("用户未激活，激活信息已再次发送至邮箱"+user.getUlogon()+"，请注意查收...");
				}else{
					//再次发送失败
					jm.setCode(0);
					jm.setMsg("用户未激活，邮箱发送失败，请联系管理员...");
				}
			}else{
				//证明是已注册
				jm.setCode(0);
				jm.setMsg("该邮箱已经被注册，请更换邮箱...");
			}
		}else{
			backuser=null;
			backuser=iub.adduser(user,localhref);
			if(backuser!=null){
				//用户注册成功
				jm.setCode(1);
				jm.setObj(backuser);
			}else{
				//注册失败
				jm.setCode(0);
				jm.setMsg("用户注册过程异常错误，请等待管理员解决...\t给您造成的不便，嗨扑米深表歉意");
				
			}
		}
		super.outData(response, jm);
	}

	/**
	 *   前端用， 用户登录
	 * @param request
	 */
	private void login(HttpServletRequest request,HttpServletResponse response) {
		JsonModel jm=new JsonModel();
		haipumi_user user=null;
		try {
			user=RequestUtil.parseRequest(request,haipumi_user.class );
			//判断验证码的正确性
			HttpSession session=request.getSession();
			String safecode=user.getSafecode();
			if(!session.getAttribute(CommonData.CODESESSION).equals(safecode)){
				jm.setCode(0);
				jm.setMsg("验证码错误");
			}else{
				//调用bizimpl
				user=iub.login(user);
				if(user!=null){
					//找到了用户   存到session中，并返回jm
					session.setAttribute(CommonData.USERSESSION, user);
					jm.setCode(1);
					jm.setObj(user);
				}else{
					jm.setCode(0);
					jm.setMsg("没有此用户或者用户名密码错误，请确认后重新输入...");
				}
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.outData(response, jm);
	}

}
